<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" destroy-on-close @closed="$emit('closed')" :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true" fullscreen>
        <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="130" ref="dialogForm" style="height: calc(100vh - 120px);overflow-y: auto;overflow-x: hidden;">
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6" v-if="mode != 'add'">
                    <el-form-item label="加工单号" prop="purchase_process_code">
                        <el-input v-model="form.purchase_process_code" placeholder="加工单号" readonly></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6">
                    <el-form-item label="加工厂" prop="process_factory">
						<el-select v-model="form.process_factory" placeholder="请选择" filterable @change="applyChange(form.process_factory)">
							<el-option v-for="item in applyList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"></el-option>
						</el-select>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="品名" prop="goods_id">
						<el-input v-model="form.goods_name" placeholder="品名" readonly @click="checkGoods(1)"></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="工艺" prop="process_type">
                        <el-input v-model="form.process_type" placeholder="请输入工艺" clearable></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="需方" prop="buyer_id">
                        <el-input v-model="buyer_name" placeholder="请选择需方" readonly @click="checkBuyer"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6">
                    <el-form-item label="联系人" prop="linkman">
						<el-input v-model="applyInfo.linkman" placeholder="联系人" readonly></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="联系方式" prop="mobile">
						<el-input v-model="applyInfo.mobile" placeholder="联系方式" readonly></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="加工日期" prop="process_date">
						<el-date-picker v-model="form.process_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%" @change="processChange"/>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="交货日期" prop="deliver_date">
                        <!-- <el-input v-model="form.deliver_date" placeholder="请输入交货日期" clearable></el-input> -->
                        <el-date-picker v-model="form.deliver_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="12">
                    <el-form-item label="供应地址" prop="address">
						<el-input v-model="applyInfo.address" placeholder="供应地址" readonly></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="克重" prop="weight">
						<el-input v-model="form.weight" placeholder="克重" clearable>
                            <template #append>克/米</template>
                        </el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="单价" prop="price">
						<el-input v-model="form.price" placeholder="单价" clearable>
                            <template #append>元/米</template>
                        </el-input>
					</el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="12">
                    <el-form-item label="备注" prop="remark">
						<el-input v-model="form.remark" placeholder="备注" clearable></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="地区" prop="area_id">
						<el-select v-model="form.area_id" placeholder="请选择" filterable clearable>
							<el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="门幅" prop="door">
						<el-input v-model="form.door" placeholder="门幅" clearable type="number" @mousewheel.prevent>
                            <template #append>米</template>
                        </el-input>
					</el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1"> 
                <el-col :span="12">
                    <el-form-item>
                        <el-input v-model="form.content" :rows="7" clearable type="textarea"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="模版" prop="template_id">
						<el-select v-model="form.template_id" placeholder="请选择" filterable clearable @change="templateChange(form.template_id)">
							<el-option v-for="item in templateList" :key="item.id" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
                </el-col>
            </el-row>
            
            <!-- 入库单 -->
            <el-form-item>
                <el-link type="primary" style="margin-right: 20px" :underline="false" @click="checkArrival">入库单选择</el-link>
                <el-tag v-for="(item,index) in houseList" :key="index" :closable="mode != 'show'" type="info" style="margin-right: 20px" @close="delHouse(index)">
                    {{ item.code }}
                </el-tag>
            </el-form-item>

             <!-- 原样本选择 -->
            <el-form-item v-if="is_select_sample">
                <el-link type="primary" style="margin-right: 20px" :underline="false">原样本</el-link>
                <el-radio-group v-model="form.old_color" class="ml-4" @change="get_color">
					<el-radio v-for="(item,index) in oldSampleList" :key="index" :label="item.name" size="large">{{item.name}}</el-radio>
				</el-radio-group>
            </el-form-item>
            <!-- 样本选择 -->
            <el-form-item>
                <el-link type="primary" style="margin-right: 20px" :underline="false" @click="checkSample">样本选择</el-link>
                <div style="margin-right: 20px;">
                    <el-image v-if="sample_image" style="width: 100px; height: 100px; border-radius: 5px;" :src="sample_image" :preview-src-list="[sample_image]" preview-teleported="true" hide-on-click-modal align="center"></el-image>
                    <div>{{sample_name}}</div>
                </div>
                <el-checkbox v-if="sampleList.length > 0" v-model="select_all" size="large" label="全选" @change="changeAll(select_all)" />
                <div style="margin-left: 20px;">
                    <el-checkbox v-for="(item,index) in sampleList" :key="index" v-model="item.show" size="large" :label="item.name" @change="sampleChange(item)" />
                </div>
            </el-form-item>

            <!-- 原花型选择 -->
            <el-form-item>
                <el-link type="primary" style="margin-right: 20px" :underline="false">原花型</el-link>
                <el-radio-group v-model="form.old_flower" class="ml-4" @change="get_color">
					<el-radio v-for="(item,index) in oldFlowerList" :key="index" :label="item.flower" size="large">{{item.flower}}</el-radio>
				</el-radio-group>
            </el-form-item>
            
            <!-- 花型选择 -->
            <el-form-item>
                <el-link type="primary" style="margin-right: 20px" :underline="false" @click="checkFlower">花型选择</el-link>
                <el-tag v-for="(item,index) in flowerList" :key="index" :closable="mode != 'show'" type="info" style="margin-right: 20px" @close="delTag(index)">
                    <el-popover placement="top-start" :width="500" trigger="hover">
                        <el-image v-if="item?.flower_image" style="width: 400px; height: 400px; border-radius: 5px;" :src="item.flower_image" :preview-src-list="[item.flower_image]" preview-teleported="true" hide-on-click-modal align="center"></el-image>
                        <template #reference>
                            {{ item.flower }}
                        </template>
                    </el-popover>
                </el-tag>
            </el-form-item>

            <!-- 颜色的库存数量 -->
            <!-- <div class="ware_color_list">
                <div class="color_name" v-for="(item,index) in ware_color_list" :key="index">
                    {{ item.color_name }}: {{ item.ware_number }}
                </div>
            </div> -->

            <!-- 数组 -->
            <sc-form-table class="formtable" ref="table" v-model="order_detail" hideAdd hideDelete placeholder="暂无数据" :show-summary="mode != 'show'" :summary-method="handleSummary" :cellStyle="cellStyle" showIndex>
                <el-table-column :label="flower_color_name" align="center" prop="index" width="200"></el-table-column>
                <el-table-column label="花型" align="center">
                    <template #default="scope">
                        {{scope.row.flower}}
                    </template>
                </el-table-column>
                <el-table-column v-for="(item,index) in table_list" :key="index" :label="item.name" :prop="item.prop" align="center" class-name="input_input">
                    <template #header>
                        <div style="display: flex;align-items: center;justify-content: center;">
                            <el-popover placement="top" :width="200" trigger="click" v-model="popover">
                                <template #reference>
                                    <div @click="getFocus(item.prop)">{{item.name}}</div>
                                </template>
                                <div style="display: flex;align-items: center;">
                                    <el-input v-model="all_set_number" type="number" :ref="item.prop + '_color'" @mousewheel.prevent @input="color_input(item,$event)"></el-input>
                                </div>
                            </el-popover>
                        </div>
                    </template>
                    <template #default="scope">
                        <div v-if="mode != 'show'">
                            <el-input v-if="scope.$index != 0" v-model="scope.row[item.prop]" type="number" @mousewheel.prevent placeholder="" @focus="common.inputFocus($event)" @input="totalComputed(scope.row)" class="inputDeep"></el-input>
                            <div v-if="scope.$index == 0 && !is_select_sample">{{item.ware_number}}</div>
                            <div v-else>{{scope.row.is_select_sample_number}}</div>
                        </div>
                        <div v-else>
                            <!-- a{{scope.row.ware_obj}}
                            b{{item.prop}} -->
                            <span v-if="scope.$index == 0">{{item.ware_number}}</span>
                            <span v-else>{{scope.row.ware_obj[item.prop]}}/{{scope.row.total_obj[item.prop]}}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="订单数" align="center" prop="number" v-if="mode != 'show'">
                    <template #header>
                        <div style="display: flex;align-items: center;justify-content: center;">
                            <el-popover placement="top" :width="200" trigger="click" v-model="popover">
                                <template #reference>
                                    <div @click="getFocusNumber">订单数</div>
                                </template>
                                <div style="display: flex;align-items: center;">
                                    <el-input v-model="set_number" type="number" ref="numberInput" @mousewheel.prevent @input="number_input"></el-input>
                                </div>
                            </el-popover>
                        </div>
                    </template>
                    <template #default="scope">
                        <span v-if="scope.$index != 0">
                            <el-input v-model="scope.row.number" type="number" @mousewheel.prevent placeholder="" @focus="common.inputFocus($event)" @input="totalComputed(scope.row)" class="inputDeep" :readonly="scope.$index == 0"></el-input>
                        </span>
                        <span v-else></span>
                    </template>
                </el-table-column>
                <el-table-column label="合计" align="center" prop="total_number"><!--  v-if="mode != 'show'" -->
                    <template #default="scope">
                        <span v-if="scope.$index != 0">
                            {{scope.row.total_number}}
                        </span>
                        <span v-else></span>
                    </template>
                </el-table-column>
                <el-table-column label="备注" align="center" width="200" v-if="mode != 'show'">
                    <template #default="scope">
                        <el-input v-if="scope.$index != 0" v-model="scope.row.remark" @mousewheel.prevent placeholder="备注" clearable></el-input>
                    </template>
                </el-table-column>
            </sc-form-table>

        </el-form>
        <el-footer style="text-align: right;position: fixed;bottom: 0;right: 0;left: 0;padding: 10px 20px;background: #fff;border-top: 1px solid #eee;">
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(0)">保存</el-button>
		</el-footer>

        <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsBack" @closed="dialog.goods = false" :query="{is_show: 1, has_stock: 1}"></select-goods>
        <select-house v-if="dialog.house" ref="houseDialog" @success="houseBack" @closed="dialog.house = false" :query="{goods_id: form.goods_id, status: 1, can_use: 1,process_factory: applyInfo.apply_name}"></select-house><!-- ware_id: applyInfo.ware_id, -->

        <select-flower v-if="dialog.flower" ref="flowerDialog" @success="flowerBack" @closed="dialog.flower = false" :query="{apply_id: form.process_factory,no_apply: 1, no_apply_type: 2}"></select-flower><!-- 花型选择 -->
        <select-sample v-if="dialog.sample" ref="sampleDialog" @success="sampleBack" @closed="dialog.sample = false" :query="{apply_id: form.process_factory,no_apply: 1, no_apply_type: 1}"></select-sample><!-- 样本选择 -->

                
        <buyer-list v-if="dialog.buy" ref="buyDialog" @success="buyBack" @closed="dialog.buy = false"></buyer-list>
    </el-dialog>
</template>

<script>

import selectGoods from '@/views/basic/goods/selectGoods.vue';
import SelectHouse from '../selectHouse.vue';

import SelectFlower from '../selectFlower.vue';
import SelectSample from '../selectSample.vue';

import BuyerList from '@/views/basic/buyer/buyerList.vue';
export default {
    emits: ['success', 'closed'],
    components: { selectGoods, SelectHouse, SelectFlower, SelectSample, BuyerList},
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '新增加工单',
                copy: '新增加工单',
                edit: '编辑加工单',
                show: '查看加工单',
            },
            visible: false,
            isSaveing: false,
            form: {
                id: "",
                process_date: this.moment().format('YYYY-MM-DD'),
                deliver_date: this.moment().add(3, 'days').format('YYYY-MM-DD'),
                process_type: "",
                ware_id: "",
                process_factory: "",
                goods_id: "",
                goods_name: "",
                price: "",
                weight: "",
                total_num: "",
                remark: "",
                area_id: "",
                door: "2.8",

                purchase_ware_ids: [],
                order_detail: [],

                old_flower: "",

                buyer: "",
                new_color_all: "",
            },
            info: {
                purchase_code: "",
                apply_name: "",
                plan_type_text: "",
                linkman: "",
                mobile: "",
                total_num: "",
                deliver_num: "",
            },
            rules: {
                ware_id: [ {required: true, message: '请选择仓库'} ],
                process_date: [ {required: true, message: '请选择加工日期'} ],
                area_id: [ {required: true, message: '请选择地区'} ],
            },
            dialog: {
                goods: false,
                house: false,
                flower: false,
                sample: false,
            },
            order_detail: [],


            
            wareList: [],
            applyList: [],
            areaList: [],
            templateList: [],
            applyInfo: {
                linkman: "",
                mobile: "",
                address: "",
                ware_id: "",
            },
            houseList: [],
            select_all: false,
            sampleList: [],
            table_list: [],
            flowerList: [],
            edit_order_detail: [],


            oldFlowerList: [],
            oldSampleList: [],
            is_select_sample: false,
            flower_color_name: "",
            select_ware_color_list: [],
            ware_color_list: [],
            select_sample_list: [],
            is_unshift: 0,
            all_set_number: "",
            set_number: "",
            buyer_name: "",
            sample_name: "",
            sample_image: "",
        }
    },
    created() {
        // this.color_input = this.common.debounce(this.color_input, 1000);
	},
    mounted() {
		this.getWare();
		this.getArea();
		this.getTemplate();
		this.getApply();
    },
    methods: {
        cellStyle(row){
            let cellStyle = '';
            if(row.columnIndex != 0  && row.column.label != '花型' && row.column.label != '备注' && row.column.label != '合计' && row.column.fixed != 'left'){
                cellStyle = {backgroundColor:'#FFF'}
            }else {
                cellStyle = {backgroundColor:'#f4f4f5'}
            }
            return cellStyle
        },
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        //表单提交方法
        submit() {
            let flower = []
            this.flowerList.map(item=>{
                flower.push({
                    flower: item.flower,
                    flower_image: item.flower_image,
                })
            })
            this.form.select_flower_param = flower
            let sample = []
            let all_sample = []
            this.sampleList.map(item=>{
                if(item.show){
                    sample.push(item.name)
                }
                all_sample.push(item.name)
            })
            this.form.select_colors = sample.join(',')
            this.form.new_color_all = all_sample.join(',')
            let array = []
            let count = 0
            this.order_detail.map(item=>{
                if(item.number){
                    array.push(item)
                }
                if(item.total_number){
                    count = Number(item.total_number) + count
                }
            })
            this.form.total_num = count
            this.form.order_detail = array
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    var res = [];
                    if (this.form.id) {
                        res = await this.$API.business.machining.order.edit.post(this.form);
                    } else {
                        res = await this.$API.business.machining.order.add.post(this.form);
                    }
                    this.isSaveing = false;
                    if (res.code == 1) {
                        this.visible = false;
                        this.$emit('success', this.form, this.mode)
                        this.$message.success("操作成功")
                    } else {
                        this.$alert(res.message, "提示", {type: 'error'})
                    }
                }
            })
        },
        //表单注入数据
        async setData(data,val) {
            if(!val){
                this.form.id = data.id
                this.form.purchase_process_code = data.purchase_process_code
            }
            var res = await this.$API.business.machining.order.detail.get({id: data.id});
            this.form.process_factory = res.data.process_factory
            this.applyInfo.apply_name = res.data.processFactory?.apply_name
            this.form.goods_id = res.data.goods_id
            this.form.goods_name = res.data.goods_name
            this.form.buyer_id = res.data.buyer_id
            this.buyer_name = res.data.buyer?.buyer_name
            this.form.process_type = res.data.process_type
            this.form.process_date = res.data.process_date
            this.form.deliver_date = res.data.deliver_date
            this.form.weight = res.data.weight
            this.form.price = res.data.price
            this.form.remark = res.data.remark
            this.form.area_id = res.data.area_id
            this.form.door = res.data.door
            this.form.content = res.data.content
            this.form.template_id = res.data.template_id
            this.form.purchase_ware_ids = res.data.purchase_ware_ids
            this.form.select_colors = res.data.select_colors
            this.sample_name = res.data.select_sample_param?.title 
            this.sample_image = res.data.select_sample_param?.image
            this.form.old_color = res.data.old_color
            this.form.old_flower = res.data.old_flower
            let house = []
            res.data.purchase_ware_ids_code.map(item=>{
                house.push({
                    id: item.id,
                    code: item.purchase_ware_code,
                })
            })
            this.houseList = house
            let sample = []
            let color = res.data.new_color_all.split(',')
            color.map(item=>{
                sample.push({
                    show: res.data.select_colors.includes(item),
                    name: item
                })
            })
            this.sampleList = sample
            this.flowerList = res.data.select_flower_param
            let colorName = []
            res.data.order_detail[0].color_data.map(item=>{
                if(res.data.select_colors.includes(item.color_name)){
                    colorName.push({
                        name: {
                            name: item.color_name,
                            enter_number: 0,
                            total_number: 0,
                        },
                        number: item.number
                    })
                }
            })
            this.table_list = colorName
            this.edit_order_detail = res.data.order_detail
            let array = []
            res.data.order_detail.map((item,index)=>{
                res.data.select_flower_param.map(item2=>{
                    if(item.flower == item2.flower){
                        const dynamicFields = Object.fromEntries(
                            this.table_list.map(item1 => {
                                const colorItem = item.color_data.find(c => c.color_name === item1.name.name);
                                return [item1.name.name, colorItem?.number || 0];
                            })
                        );
                        array.push({
                            index: index + 1,
                            flower: item2.flower,
                            color_data: item.color_data,
                            flower_image: item2.flower_image,
                            remark: item.remark,
                            number: item.order_count,
                            total_number: item.total_count,
                            ware_obj: {},
                            total_obj: {},
                            ...dynamicFields
                        })
                    }
                })
            })
            // if(this.mode != 'show'){
                array.unshift([])
            // }
            this.order_detail = array
            this.updateTableList()
            setTimeout(() => {
                let apply = this.applyList.find(item => item.apply_id == res.data.process_factory)
                this.applyInfo.linkman = apply.linkman
                this.applyInfo.mobile = apply.mobile
                this.applyInfo.address = apply.address
                this.applyInfo.ware_id = apply.ware_id
                if(apply.sample_data.length == 0){
                    this.is_select_sample = false
                }else {
                    this.is_select_sample = true
                }
                if(!this.is_select_sample){
                    this.flower_color_name = `原花型${this.form.old_flower}`
                }else{
                    this.flower_color_name = `原花型${this.form.old_flower}原颜色${this.form.old_color}`
                }
                this.edit_get()
            }, 100);
            this.select_sample_list = this.sampleList.filter(item => item.show)
        },
        // 重新获取原花型
        async edit_get(){
            let array = []
            this.houseList.map(item=>{
                array.push(item.id)
            })
            this.form.purchase_ware_ids = array
            if(!array.length)return
            var res = await this.$API.business.machining.order.get_can_color.post({purchase_ware_ids: array,old_flower: this.form.old_flower,})
            this.oldFlowerList = res.data.select_flower_param
            let ware = []
            res.data.order_detail.map(item=>{
                if(item.flower == this.form.old_flower){
                    item.color_data.map(item1=>{
                        ware.push({
                            color_name: item1.color_name,
                            ware_number: item1.can_use_number
                        })
                    })
                }
            })
            if(this.form.id){
                let sample = []
                let color = res.data.select_colors.split(',')
                color.map(item=>{
                    sample.push({
                        show: this.form.select_colors.includes(item),
                        name: item
                    })
                })
                if(this.is_select_sample){
                    this.oldSampleList = sample
                }else {
                    this.sampleList = sample
                    this.select_sample_list = this.sampleList.filter(item => item.show)
                }
            }
            this.select_ware_color_list = ware
            this.getWareNum()
        },
        // 地区列表
		async getWare() {
			var res = await this.$API.basic.ware.all.get();
			this.wareList = res.data
		},
        // 地区列表
		async getArea() {
			var res = await this.$API.basic.area.all.get();
			this.areaList = res.data
		},
        // 供应商列表
		async getApply() {
			var res = await this.$API.basic.apply.all.get({type: 3});
			this.applyList = res.data
		},
        applyChange(e){
            this.houseList = []
            this.order_detail = []
            this.oldFlowerList = []
            this.flowerList = []
            this.oldSampleList = []
            this.sampleList = []
            this.table_list = []
            this.form.goods_id = ""
            this.form.goods_name = ""
            this.form.old_flower = ""
            this.form.old_color = ""
            this.flower_color_name = ""
            this.select_all = false
            this.is_unshift = 0

            let apply = this.applyList.find(item => item.apply_id == e)
            this.applyInfo.linkman = apply.linkman
            this.applyInfo.mobile = apply.mobile
            this.applyInfo.address = apply.address
            this.applyInfo.ware_id = apply.ware_id
            this.applyInfo.apply_name = apply.apply_name
            if(apply.sample_data.length == 0){
                this.is_select_sample = false
            }else {
                this.is_select_sample = true
            }
        },
        // 模版列表
		async getTemplate() {
			var res = await this.$API.basic.print.all.get();
			this.templateList = res.data
		},
        templateChange(e){
            let template = this.templateList.find(item => item.id == e)
            this.form.content = template.content
        },
        // 选择商品
        checkGoods(e){
            this.dialog.goods = true
            this.$nextTick(() => {
                this.$refs.goodsDialog.open('add').setData(e)
            })
        },
        // 选择商品返回
        goodsBack(data){
            this.form.goods_id = data.id
            this.form.goods_name = data.name
        },

        // 选择入库单
        checkArrival(){
            if(this.mdoe == 'show') return
            if(!this.form.process_factory || !this.form.goods_id){
                this.$message.error('请先选择加工厂和品名')
                return
            }
            this.dialog.house = true
            this.$nextTick(() => {
                this.$refs.houseDialog.open('add').setData(1,'process')
            })
        },
        // 选择入库单返回
        houseBack(data){
            this.form.buyer_id = data[0].buyer_id
            this.buyer_name = data[0].buyer?.buyer_name
            let array = []
            data.map(item=>{
                array.push({
                    id: item.id,
                    code: item.purchase_ware_code
                })
            })
            this.houseList = array
            if(this.houseList.length){
                this.get_color()
            }
        },
        // 长接口返回
        async get_color(){
            if(!this.is_select_sample){
                this.flower_color_name = `原花型${this.form.old_flower}`
            }else{
                this.flower_color_name = `原花型${this.form.old_flower}原颜色${this.form.old_color}`
                
            }
            let array = []
            this.houseList.map(item=>{
                array.push(item.id)
            })
            this.form.purchase_ware_ids = array
            if(!array.length)return
            var res = await this.$API.business.machining.order.get_can_color.post({purchase_ware_ids: array,old_flower: this.form.old_flower,})
            let sample = []
            let color = res.data.select_colors.split(',')
            color.map(item=>{
                sample.push({
                    name: item
                })
            })
            if(!this.is_select_sample){
                this.sampleList = this.select_sample_list.length ? this.select_sample_list : sample
            }else {
                this.oldSampleList = sample
            }
            let ware = []
            res.data.order_detail.map(item=>{
                if(item.flower == this.form.old_flower){
                    item.color_data.map(item1=>{
                        ware.push({
                            color_name: item1.color_name,
                            ware_number: item1.can_use_number
                        })
                    })
                }
            })
            this.select_ware_color_list = ware
            this.oldFlowerList = res.data.select_flower_param
            this.edit_order_detail = res.data.order_detail
            this.getWareNum()
            this.is_unshift ++
            this.getDbData()
        },
        getDbData(){ 
            let array_data = []
            this.flowerList.map((item,index)=>{
                let exist = this.common.isExist(item.flower_image, this.order_detail, 'flower_image')
                if (exist) {
                    return
                }
                array_data.push({
                    index: index + 1,
                    flower: item.flower,
                    flower_image: item.flower_image,
                    number: 1,
                })
            })
            console.log('array_data :>> ', array_data);
            console.log('this.is_unshift :>> ', this.is_unshift);
            if(this.mode == 'add' && this.is_unshift == 1){
                array_data.unshift([])
            }
            this.order_detail = [...this.order_detail, ...array_data]
            this.updateTableList()
        },
        changeAll(e){
            this.sampleList.map(item=>{
                item.show = e
            })
            this.getWareNum()
            this.updateTableList();
        },
        sampleChange(e){
            if(e.show == false){
                this.select_all = false
            }
            this.getWareNum()
            this.updateTableList();
        },
        // 数组数字赋值
        getWareNum(){
            this.select_sample_list = this.sampleList.filter(item => item.show)
            // let array = []
            // this.select_ware_color_list.map(item=>{
            //     this.sampleList.map(item1=>{
            //         if(item1.show && item.color_name == item1.name){
            //             array.push({
            //                 color_name: item.color_name,
            //                 ware_number: item.ware_number
            //             })
            //         }
            //     })
            // })
            // this.ware_color_list = array
            if(this.is_select_sample){
                this.select_ware_color_list.map(item=>{
                    if(this.form.old_color == item.color_name){
                        this.order_detail[0].is_select_sample_number = `${this.form.old_color}: ${item.ware_number}`
                    }
                })
            }else {
                this.$nextTick(()=>{ 
                    this.table_list.map(item=>{
                        this.select_ware_color_list.map(item2=>{
                            if(item2.color_name == item.name){
                                item.name = item2.color_name,
                                item.ware_number = item2.ware_number
                            }
                        })
                    })
                })
            }
        },
        updateTableList() {
            this.table_list = this.sampleList.filter(item => item.show)
            .map(item => ({
                name: item.name,
                prop: item.name
            }));
            this.order_detail = this.order_detail.map((row,index) => {
                const newRow = { ...row };
                // this.table_list.forEach(col => {
                //     newRow[col.prop] = newRow[col.prop] || 0;
                // });
                this.table_list.forEach(col => {
                    newRow[col.prop] = newRow[col.prop] || 0;
                    if(this.mode == 'show' && index != 0){
                        newRow.color_data.map(item1=>{
                            if(item1.color_name == col.prop){
                                newRow.ware_obj[col.prop] = item1.ware_number,
                                newRow.total_obj[col.prop] = Number(item1.number) * Number(row.number)
                            }
                        })
                        console.log('newRow :>> ', newRow);
                    }
                });
                this.totalComputed(newRow)
                return newRow;
            });
        },
        delTag(index){
            // this.$confirm(`确定删除吗？`, '提示', {
            //     type: 'warning'
            // }).then(() => {
            //     this.flowerList.splice(index,1)
            //     this.order_detail.splice(index+1,1)
            //     this.order_detail.forEach((item,index) => {
            //         item.index = index
            //     })
            // }).catch(() => {})
            this.flowerList.splice(index,1)
            this.order_detail.splice(index+1,1)
            this.order_detail.forEach((item,index) => {
                item.index = index
            })
        },
        delHouse(index){
            // this.$confirm(`确定删除吗？`, '提示', {
            //     type: 'warning'
            // }).then(() => {
            //     this.select_all = false
            //     this.changeAll(false)
            //     this.houseList.splice(index,1)
            //     this.get_color()
            // }).catch(() => {})
            this.select_all = false
            this.changeAll(false)
            this.houseList.splice(index,1)
            this.get_color()
        },
        totalComputed(row){
            let count = 0
            this.table_list.map(item=>{
                count = Number(row[item.prop]) + count
                row.total_number = count
            })
            if(count && row.number){
                row.total_number = count * Number(row.number)
            }
        },
        // 样本选择
        checkSample(){
            if(this.mdoe == 'show') return
            if(!this.is_select_sample) return
            if(!this.form.process_factory) return this.$message.error('请先选择加工厂')
            this.dialog.sample = true
            this.$nextTick(() => {
                this.$refs.sampleDialog.open('add').setData(1)
            })
        },
        // 样本返回
        sampleBack(data){
            let array = []
            let color = data.colors.split(',')
            color.map(item=>{
                array.push({
                    name: item
                })
            })
            this.sampleList = array
        },
        // 选择花型
        checkFlower(){
            if(!this.form.process_factory) return this.$message.error('请先选择加工厂')
            if(!this.form.old_flower) return this.$message.error('请先选择原花型')
            let query = {
                apply_id: this.form.apply_id,
                goods_id: this.form.goods_id,
                is_select: this.flowerList.map(item => item.flower)
            }
            this.dialog.flower = true
            this.$nextTick(() => {
                this.$refs.flowerDialog.open('add').setData(query)
            })
        },
        // 花型返回
        flowerBack(data){
            let array = []
            data.map((item,index) =>{
                let exist = this.common.isExist(item.flower_image, this.flowerList, 'flower_image')
                if (exist) {
                    return
                }
                array.push({
                    index: index + 1,
                    flower: item.flower,
                    flower_image: item.flower_image,
                    number: 1
                })
            })
            this.flowerList = [...this.flowerList, ...array]
            // this.order_detail = [...this.order_detail, ...array]
            // this.updateTableList()
            this.get_color()
        },

        handleSummary({ columns, data }) {
            const sums = [];
            // 过滤出非样本行
            const validRows = data.filter(item => !item.is_select_sample_number && item.flower);
            
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '';
                    return;
                }
                if (index === 1) {
                    sums[index] = '合计';
                    return;
                }
                
                // 订单数列特殊处理：计算所有行订单数总和
                if (column.property === 'number') {
                     data.map(item1 => {
                        if(item1.name == '提交数据'){
                            const orderNumbers = validRows.map(row => Number(row.number)).filter(num => !isNaN(num));
                            sums[index] = orderNumbers.reduce((sum, num) => sum + num, 0);
                            return;
                        }
                    });
                }
                
                // 合计数量列特殊处理：计算所有颜色数量乘以各自行订单数的总和
                if (column.property === 'total_number') {
                    let total = 0;
                    validRows.forEach(row => {
                        // 从totalComputed方法逻辑看，total_number已经是计算过的合计值
                        const rowTotalNumber = Number(row.total_number) || 0;
                        total += rowTotalNumber;
                    });
                    sums[index] = total;
                    return;
                }
                
                // 颜色列特殊处理：该列每行值乘以行订单数后累加
                const isColorColumn = this.table_list.some(item => item.prop === column.property);
                if (isColorColumn) {
                    let total = 0;
                    validRows.forEach(row => {
                        const rowValue = Number(row[column.property]) || 0;
                        const rowOrderNumber = Number(row.number) || 0;
                        total += rowValue * rowOrderNumber;
                    });
                    sums[index] = total;
                    return;
                }
                
                // 其他列保持原有累加逻辑
                const values = validRows.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr;
                        } else {
                            return prev;
                        }
                    }, 0);
                } else {
                    sums[index] = '';
                }
            });
            return sums;
        },
        // 选择需方
        checkBuyer(){
            this.dialog.buy = true
            this.$nextTick(() => {
                this.$refs.buyDialog.open('add').setData(1)
            })
        },
        // 需方返回
        buyBack(data){
            this.form.buyer_id = data.id
            this.buyer_name = data.buyer_name
        },
        processChange(e){
            this.form.deliver_date = this.moment(e).add(3, 'days').format('YYYY-MM-DD')
        },
        // 批量设置数量
        color_input(color,e){
            this.order_detail.map(item=>{
                item[color.prop] = e
                this.totalComputed(item)
            })
            // this.all_set_number = ""
        },

        getFocus(item){
            this.all_set_number = ""
            let e = `${item}_color`
            setTimeout(()=>{ 
                this.$nextTick(()=>{
                    this.$refs[e][0].focus()
                })
            },100)
        },
        getFocusNumber(){
            this.set_number = ""
            setTimeout(()=>{ 
                this.$nextTick(()=>{
                    this.$refs.numberInput.focus()
                })
            },100)
        },
        number_input(e){ 
             this.order_detail.map( item =>{
                item.number = e
                this.totalComputed(item);
            })
        },
    }
}
</script>

<style lang="scss" scoped>

:deep(.el-input input[type="number"]::-webkit-outer-spin-button),   
:deep(.el-input input[type="number"]::-webkit-inner-spin-button) {
   -webkit-appearance: none;
   margin: 0;   
}
   
:deep(.el-input input[type="number"]) {
   -moz-appearance: textfield;
}
.inputDeep {
    .el-input__inner {
        cursor: default !important;
        text-align: center;
    }
    :deep(.el-input__wrapper) {
        box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
        height: 20px;
        background: transparent;
        cursor: default;
        .el-input__inner {
            cursor: default !important;
            text-align: center;
        }
    }
}

.ware_color_list{
    display: flex;
    justify-content: center;
    .color_name{
        font-size: 20px;
        font-weight: 600;
        margin: 0 40px 5px;
    }
}
</style>
